﻿#region License
/*
Copyright (c) 2010, Dilyan Rusev
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list
 of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this 
list of conditions and the following disclaimer in the documentation and/or other 
materials provided with the distribution.

* Neither the name of TU-Sofia nor the names of its contributors may be used to endorse or 
promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

using System;
using System.Linq;
using System.Windows.Forms;
using System.Collections.Generic;

namespace StoreManagement
{
    public partial class MainForm : Form
    {
        Data.Provider dbProvider;

        public MainForm()
        {
            InitializeComponent();
        }

        private void ShowError(string message)
        {
            MessageBox.Show(message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void BindGrid()
        {
            this.dataSource.DataSource = this.dbProvider.GetAllProperties();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            this.dbProvider = new Data.Provider();
            this.cbxSearch.SelectedIndex = 0;
            this.btnSearch.Enabled = false;
            this.btnCancelSearch.Enabled = false;
            this.cbxSearch.Enabled = false;            
            this.BindGrid();
        }

        

        private void MainForm_Exit(object sender, EventArgs e)
        {
            this.Close();
        }

        private void MainForm_About(object sender, EventArgs e)
        {
            MessageBox.Show("Store management.\nDilyan Rusev, 2010", "About", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void MainForm_CreateProperty(object sender, EventArgs e)
        {
            var dlg = new CreatePropertyForm();
            dlg.ShowInTaskbar = false;
            dlg.ShowIcon = false;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                var prop = dlg.Property;
                try
                {
                    this.dbProvider.CreateProperty(prop.Name, prop.Description, prop.Price, prop.State);
                    this.BindGrid();
                    this.mainStatus.Text = string.Concat(prop.Name, " was succesfully created.");
                }
                catch (Exception error)
                {
                    this.ShowError(error.Message);
                    this.mainStatus.Text = string.Concat(prop.Name, " could not be created, because '", error.Message, "'");
                }
            }
        }

        private void MainForm_DeleteSelected(object sender, EventArgs e)
        {
            var idsToDelete =
                this.grid.SelectedRows.Cast<DataGridViewRow>()
                .Select(r => ((Data.Property)r.DataBoundItem).ID);

            foreach (var id in idsToDelete)
            {
                this.dbProvider.DeleteProperty(id);
            }
            this.BindGrid();
        }

        private void grid_SelectionChanged(object sender, EventArgs e)
        {
            bool itemIsSelected = this.grid.SelectedRows.Count > 0;
            bool onlyOneItemIsSelected = this.grid.SelectedRows.Count == 1;

            this.deleteSelectedToolStripMenuItem.Enabled = itemIsSelected;
            this.btnDelete.Enabled = itemIsSelected;

            this.btnEdit.Enabled = onlyOneItemIsSelected;
            this.editSelectedToolStripMenuItem.Enabled = onlyOneItemIsSelected;
        }

        private void MainForm_EditSelected(object sender, EventArgs e)
        {
            var propertyToEdit = (Data.Property)this.grid.SelectedRows[0].DataBoundItem;
            var dlg = new EditPropertyForm(propertyToEdit);
            dlg.ShowInTaskbar = false;
            dlg.ShowIcon = false;
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {                
                var id = propertyToEdit.ID;
                propertyToEdit = dlg.Property;
                propertyToEdit.ID = id;
                try
                {
                    this.dbProvider.UpdateProperty(propertyToEdit);
                    this.BindGrid();
                }
                catch (Exception error)
                {
                    this.ShowError(error.Message);
                    this.mainStatus.Text = string.Concat(propertyToEdit.Name, " could not be updated, because '", error.Message, "'");
                }
            }
        }

        
        private void btnSearch_Click(object sender, EventArgs e)
        {
            var searchMode = this.cbxSearch.SelectedIndex;
            IEnumerable<Data.Property> searchResult;
            if (!this.txtSearch.Text.IsNullOrWhitespace())
            {
                switch (searchMode)
                {
                    case 0: // search by name and description
                        searchResult = this.dbProvider.GetPropertiesWithNameOrDescription(this.txtSearch.Text);
                        break;
                    case 1: // search by name
                        searchResult = this.dbProvider.GetPropertiesWithName(this.txtSearch.Text);
                        break;
                    case 2: // search by description
                        searchResult = this.dbProvider.GetPropertiesWithDescription(this.txtSearch.Text);
                        break;
                    default:
                        throw new NotImplementedException();
                }
            }
            else
            {
                searchResult = this.dbProvider.GetAllProperties();
            }
            this.dataSource.DataSource = searchResult;
        }

        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Escape:
                    this.MainForm_CancelSearch(this, EventArgs.Empty);
                    break;

                case Keys.Enter:
                    this.btnSearch.PerformClick();
                    break;

                default:
                    break;
            }
        }

        private void MainForm_CancelSearch(object sender, EventArgs e)
        {
            this.txtSearch.Text = string.Empty;
            this.BindGrid();
        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            if (this.txtSearch.Text.IsNullOrWhitespace())
            {
                this.btnSearch.Enabled = false;
                this.btnCancelSearch.Enabled = false;
                this.cbxSearch.Enabled = false;
            }
            else
            {
                this.btnCancelSearch.Enabled = true;
                this.btnSearch.Enabled = true;
                this.cbxSearch.Enabled = true;
            }
        }       

        void grid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            bool enabled = this.grid.RowCount > 0;

            this.btnEdit.Enabled = enabled;
            this.btnDelete.Enabled = enabled;
            this.deleteSelectedToolStripMenuItem.Enabled = enabled;
            this.editSelectedToolStripMenuItem.Enabled = enabled;    
        }
    }
}
